package com.cssy.yd.logic.service.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.byd.acegiext.domain.User;
import com.cssy.yd.logic.dao.LogicSoQuoteDAO;
import com.cssy.yd.logic.dao.LogicSoQuoteProductDAO;
import com.cssy.yd.logic.entity.LogicSoQuoteDO;
import com.cssy.yd.logic.entity.LogicSoQuoteProductDO;
import com.cssy.yd.logic.service.ILogicSoQuoteService;
import com.plat.exception.SyBaseException;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.DateUtil;
import com.plat.util.GlobalResLoader;
import com.plat.util.IDCodeTypeUtil;
import com.plat.util.SessionUtil;
import com.yuendong.sy.po.code.SyCode;
import com.yuendong.sy.service.code.SyCodeType;
import com.yuendong.sy.service.code.impl.SyCodeService;
/**
 * 销售报价业务方法
 * @author huang.xuming [2013-7-10]
 *
 */
@Service("logicSoQuoteService")
public class LogicSoQuoteServiceImpl implements ILogicSoQuoteService {
	private static final Logger logger = Logger.getLogger(LogicSoQuoteServiceImpl.class);
	
	@Resource(name = "logicSoQuoteDAO")
	LogicSoQuoteDAO logicSoQuoteDAO;
	
	@Resource(name = "logicSoQuoteProductDAO")
	LogicSoQuoteProductDAO logicSoQuoteProductDAO;
	
	@Resource(name = "syCodeService")
	private SyCodeService syCodeService;
	
	@Override
	public SearchResult findListByExample(SearchConditions scs)
			throws SyBaseException {
		SearchResult rs=new SearchResult(scs);
		List<LogicSoQuoteDO>  list=logicSoQuoteDAO.find(scs);
		rs.setRecordCount(logicSoQuoteDAO.count(scs));
		rs.setResults(list);
		return rs;
	}

	@Override
	public Integer delete(String id, User user) throws SyBaseException {
		logicSoQuoteDAO.deleteLogicSoQuoteDOByPrimaryKey(id);
		return null;
	}

	@Override
	public Integer update(LogicSoQuoteDO t, User user) throws SyBaseException {
		t.setDuuser(user.getName());
		t.setDutime(new Date());
		logicSoQuoteDAO.updateLogicSoQuoteDO(t);
		return null;
	}

	@Override
	public LogicSoQuoteDO save(LogicSoQuoteDO sodo, User user) throws SyBaseException {
		sodo.setDcruser(user.getName());
		sodo.setDctime(new Date());
		logicSoQuoteDAO.insertLogicSoQuoteDO(sodo);
		return sodo;
	}

	@Override
	public LogicSoQuoteDO findListById(String id) throws SyBaseException {
		return logicSoQuoteDAO.findLogicSoQuoteDOByPrimaryKey(id);
	}

	@Override
	public void soQuoteSave(HttpServletRequest request, LogicSoQuoteDO curAP)
			throws SyBaseException {
		try {
			
			String itemdata = request.getParameter("itemdata");
			List<LogicSoQuoteProductDO> soItemlist = JSONArray.parseArray(itemdata,
					LogicSoQuoteProductDO.class);
			
			/*
			 * 获取操作
			 * 0为保存(草稿状态)
			 * 1为提交(待审核状态)
			 * 2为二级审核(提交二级审核)
			 * 3为三级审核(提交三级审核)
			 * 4为二级结案(提交二级结案)
			 * 5为三级结案(提交三级结案)
			 * 6为二级驳回到草稿
			 * 7为三级驳回到草稿
			 */
			String paramflag = request.getParameter("paramflag");
			int iParamFlag = -1;
			iParamFlag = Integer.parseInt(paramflag);
		
			curAP.setBillstatus(iParamFlag);
			
			User user = SessionUtil.getUser(request);
			Date curDate = new Date();
			if (StringUtils.isBlank(curAP.getId())) {
				/* 新增  设置状态billstatus= 0*/
				String quoteId = IDCodeTypeUtil.getId();
				
				curAP.setId(quoteId);
				curAP.setDctime(curDate);
				curAP.setDcruser(user.getName());
				
				curAP.setLister(user.getName());
				curAP.setListerName(user.getRealName());
				
				
				//curAP.setBillstatus(0);
				
				String quoteExp = request.getParameter("quoteExp");//日期转换处理
				if(StringUtils.isNotBlank(quoteExp)){
					curAP.setQuoteExp(new Date(DateUtil.getTimeFromStr(quoteExp)));//待优化
				}
				
				curAP.setNo(syCodeService.getCode("SOQuote","SOQ",SyCode.DATE_YYMM,5));
				
				logicSoQuoteDAO.insertLogicSoQuoteDO(curAP);
				
				curAP.setId(quoteId);//添加上，否则插入之后ID为0
				saveOrUpdateItems(soItemlist, curAP);
				
			} else if(iParamFlag >= 0 && iParamFlag <=7){
				/* 修改 */
				if(0==iParamFlag){//0为保存--不执行，因有单据ID时不会变更为状态0
					curAP.setDutime(new Date());
					curAP.setDuuser(user.getName());
					
					int result =logicSoQuoteDAO.updateLogicSoQuoteDO(curAP);
					if(result==1){
						saveOrUpdateItems(soItemlist, curAP);
					}else{
						throw new SyBaseException("您修改的行数据发生改变，请重新点开查看");
					}
				}else {
					LogicSoQuoteDO bean=logicSoQuoteDAO.findLogicSoQuoteDOByPrimaryKey(curAP.getId());
					if(null == bean.getVersion() || !bean.getVersion().equals(curAP.getVersion())){
						throw new SyBaseException("版本号异常，请刷新后重新编辑");
					}
					
					bean.setBillstatus(iParamFlag);
					
					int result = 0;
//					if(1==iParamFlag){//1为提交(待审核状态)，拟稿人提交给一级审批人--拟稿人本人自审批
//						curAP.setVersion(bean.getVersion());
//						curAP.setBillstatus(bean.getBillstatus());
//						
//						curAP.setDctime(bean.getDctime());
//						curAP.setDcruser(bean.getDcruser());
//						
//						curAP.setLister(user.getName());
//						curAP.setListerName(user.getRealName());
//						curAP.setDutime(new Date());
//						curAP.setDuuser(user.getName());
//						
//						result =logicSoQuoteDAO.updateLogicSoQuoteDO(curAP);
//						if(result==1){
//							saveOrUpdateItems(soItemlist, curAP);
//						}
//					}else 
					if(2==iParamFlag ){//2为二级审核(提交二级审核)
						curAP.setVersion(bean.getVersion());
						curAP.setBillstatus(bean.getBillstatus());
						
						curAP.setDctime(bean.getDctime());
						curAP.setDcruser(bean.getDcruser());
						
						curAP.setLister(user.getName());
						curAP.setListerName(user.getRealName());
						curAP.setDutime(curDate);
						curAP.setDuuser(user.getName());
						
						String quoteExp = request.getParameter("quoteExp");//日期转换处理
						if(StringUtils.isNotBlank(quoteExp)){
							curAP.setQuoteExp(new Date(DateUtil.getTimeFromStr(quoteExp)));//待优化
						}
						
						result =logicSoQuoteDAO.updateLogicSoQuoteDO(curAP);
						if(result==1){
							saveOrUpdateItems(soItemlist, curAP);
						}
					}else if(3==iParamFlag ||4==iParamFlag || 6==iParamFlag){//3为三级审核(提交三级审核) ，二级结案(提交二级结案)，6为二级驳回到草稿
						bean.setAuditor(user.getName());//二级
						bean.setAuditorName(user.getRealName());
						result =logicSoQuoteDAO.updateLogicSoQuoteDO(bean);
					}else if(5==iParamFlag || 7==iParamFlag){//5为三级结案(提交三级结案) ，7为三级驳回到草稿
						bean.setApprover(user.getName());//二级
						bean.setApproverName(user.getRealName());
						result =logicSoQuoteDAO.updateLogicSoQuoteDO(bean);
					}
					
					if(result==0){
						throw new SyBaseException("您修改的行数据发生改变，请重新点开查看");
					}
				}
			}else{
				throw new SyBaseException("ParamFlag不合法："+iParamFlag);
			}
		} catch (Exception e) {
			//e.printStackTrace();
			logger.error(e.getMessage(), e);
			throw new SyBaseException(GlobalResLoader.getOpfailed()
					+ e.getMessage());
		}
	}

	@Override
	public void deleteProductsByQuoteId(String quoteId)
			throws DataAccessException {
		logicSoQuoteProductDAO.deleteBySoQuoteId(quoteId);
		
	}

	@Override
	public List<LogicSoQuoteProductDO> findProductsByQuoteId(String quoteId) {
		return logicSoQuoteProductDAO.findByQuoteId(quoteId);
	}

	@Override
	public List<LogicSoQuoteProductDO> findProductValidQuoteByCNoAndPNo(
			String clientNo, String productNo) {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * 单据的子项持久化
	 * @param soItemlist
	 * @param curAP
	 */
	private void saveOrUpdateItems(List<LogicSoQuoteProductDO> soItemlist ,LogicSoQuoteDO curAP){
		//删除本订单下的item
		if(null != curAP.getId()){
			logicSoQuoteProductDAO.deleteBySoQuoteId(curAP.getId());
		}
		
		//插入单据的item
		if(null != soItemlist){
			for (LogicSoQuoteProductDO soItemDO : soItemlist) {
				//对需要处理的item进行赋值
				soItemDO.setId(IDCodeTypeUtil.getId());
				soItemDO.setQuoteId(curAP.getId());
				soItemDO.setQuoteNo(curAP.getNo());
				soItemDO.setCliNo(curAP.getCliNo());
				soItemDO.setCliName(curAP.getCliName());
				
				soItemDO.setDcruser(curAP.getDcruser());
				soItemDO.setDctime(curAP.getDctime());
				
				
				soItemDO.setDuuser(curAP.getDcruser());
				soItemDO.setDutime(curAP.getDutime());
				
				soItemDO.setValidFlag(1);
				
				logicSoQuoteProductDAO.insertLogicSoQuoteProductDO(soItemDO);
			}
		}
	}

	@Override
	public Integer deleteBizRemoved(String id) throws SyBaseException {
		// TODO Auto-generated method stub
		return null;
	}
}
